package com.glb.gilibuy.service.impl;

import com.github.pagehelper.PageInfo;
import com.glb.gilibuy.dao.CartDao;
import com.glb.gilibuy.entity.*;
import com.glb.gilibuy.service.CartService;
import com.glb.gilibuy.service.ProductService;
import com.glb.gilibuy.service.UserReceiveAddressService;
import com.glb.gilibuy.util.BeanUtil;
import com.glb.gilibuy.util.MapGenerator;
import com.glb.gilibuy.util.SnowflakeIdUtil;
import com.glb.gilibuy.web.vo.CartVO;
import com.glb.gilibuy.web.vo.ProductDetailVO;
import com.glb.gilibuy.web.vo.UserReceiveAddressVO;
import com.glb.gilibuy.web.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description:
 * @Author: Yingtian qian
 * @Date: 2021/8/5 11:30
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartDao cartDao;

    @Autowired
    private ProductService productService;

    @Autowired
    private UserReceiveAddressService userReceiveAddressService;

    @Override
    public Cart selectCartByCartId(String cartId) {
        if (!"".equals(cartId)) {
            CartExample cartExample = new CartExample();
            cartExample.or().andCartIdEqualTo(cartId).andIsDeletedEqualTo(0);
            List<Cart> cartList = cartDao.selectByExample(cartExample);
            if (cartList.isEmpty()) {
                return null;
            }
            return cartList.get(0);
        }
        return null;
    }

    @Override
    public List<Cart> selectCartsByUserId(String userId) {
        if (!"".equals(userId)) {
            CartExample cartExample = new CartExample();
            cartExample.setOrderByClause("id desc");
            cartExample.or().andUserIdEqualTo(userId).andIsDeletedEqualTo(0);
            List<Cart> cartList = cartDao.selectByExample(cartExample);
            return cartList;
        }
        return null;
    }

    @Override
    public Integer selectCountByUserId(String userId) {
        if (!"".equals(userId)) {
            CartExample cartExample = new CartExample();
            cartExample.setOrderByClause("id desc");
            cartExample.or().andUserIdEqualTo(userId).andIsDeletedEqualTo(0);
            Integer count = Math.toIntExact(cartDao.countByExample(cartExample));
            return count;
        }
        return null;
    }

    @Override
    public Map<String, Object> addCart(Cart cart) {
        Product product = productService.selectProductByProductId(cart.getProductId());
        if (product == null) {
            return MapGenerator.getRes(500, "商品不存在！");
        }
        if (product.getIsVirtual() == 1) {
            return MapGenerator.getRes(503, "虚拟商品不能加入购物车！");
        }

        int num = cart.getAmount();

        Cart cartFromDB = selectCartByUserIdAndProductId(cart.getUserId(), cart.getProductId());
        if (cartFromDB != null) {
            num += cartFromDB.getAmount();
            cartFromDB.setAmount(num);
            return updateCart(cartFromDB);
        }

        if (num > product.getProductAmount()) {
            return MapGenerator.getRes(501, "添加数量超出商品库存！");
        }

        //超出最大数量
        int totalItem = selectCountByUserId(cart.getUserId()) + 1;
        if (totalItem > 99) {
            return MapGenerator.getRes(502, "超出购物车最大容量！");
        }

        cart.setCartId(String.valueOf(SnowflakeIdUtil.getSnowflakeId()));
        cart.setGmtCreate(new Date());
        cart.setIsDeleted(0);
        if (cartDao.insertSelective(cart) > 0) {
            return MapGenerator.getRes(200, "加入购物车成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> updateCart(Cart cart) {
        Cart cartFromDB = selectCartByCartId(cart.getCartId());
        if (cartFromDB == null) {
            return MapGenerator.getRes(500, "记录不存在！");
        }
        if (!cart.getUserId().equals(cartFromDB.getUserId())) {
            return MapGenerator.getRes(501, "无权限修改！");
        }
        if (cart.getAmount().equals(cartFromDB.getAmount())) {
            return MapGenerator.getRes(200, "修改成功！");
        }
        Product product = productService.selectProductByProductId(cartFromDB.getProductId());
        int num = cart.getAmount();
        if (num > product.getProductAmount()) {
            return MapGenerator.getRes(502, "修改数量超出商品库存！");
        }
        cartFromDB.setAmount(num);
        if (cartDao.updateByPrimaryKeySelective(cartFromDB) > 0) {
            return MapGenerator.getRes(200, "修改成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public Map<String, Object> deleteCart(Cart cart) {
        Cart cartFromDB = selectCartByCartId(cart.getCartId());
        if (cartFromDB == null) {
            return MapGenerator.getRes(500, "记录不存在！");
        }
        if (!cart.getUserId().equals(cartFromDB.getUserId())) {
            return MapGenerator.getRes(501, "无权限删除！");
        }
        cartFromDB.setIsDeleted(1);
        if (cartDao.updateByPrimaryKeySelective(cartFromDB) > 0) {
            return MapGenerator.getRes(200, "删除成功！");
        }
        return MapGenerator.getRes(520, "内部错误！");
    }

    @Override
    public PageInfo findCartsByUserId(String userId) {
        List<Cart> cartList = selectCartsByUserId(userId);
        if (cartList.isEmpty()) {
            return null;
        }
        PageInfo pageInfo = new PageInfo(cartList);
        List<CartVO> cartVOList = BeanUtil.copyList(cartList, CartVO.class);
        for (CartVO cartVO : cartVOList) {
            Product product = productService.selectProductByProductId(cartVO.getProductId());
            cartVO.setProductName(product.getProductName());
            cartVO.setProductPrice(product.getProductPrice());
            cartVO.setProductTotalPrice(cartVO.getProductPrice().multiply(new BigDecimal(cartVO.getAmount())));
        }
        pageInfo.setList(cartVOList);
        return pageInfo;
    }

    @Override
    public Map<String, Object> findSelectedCarts(String[] cartIds, HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        String userId = userTemp.getUserId();

        List<CartVO> cartVOList = new ArrayList<>();
        BigDecimal totalPrice = new BigDecimal(0);

        for (String cartId : cartIds) {
            Cart cart = selectCartByCartId(cartId);
            if (cart == null) {
                return MapGenerator.getRes(500, "存在错误的购物车id！");
            }
            if (!cart.getUserId().equals(userId)) {
                return MapGenerator.getRes(501, "无权限访问！");
            }
            CartVO cartVO = new CartVO();
            BeanUtil.copyOne(cart, cartVO);
            Product product = productService.selectProductByProductId(cart.getProductId());
            cartVO.setProductName(product.getProductName());
            cartVO.setProductPrice(product.getProductPrice());
            cartVO.setProductTotalPrice(cartVO.getProductPrice().multiply(new BigDecimal(cartVO.getAmount())));
            totalPrice = totalPrice.add(cartVO.getProductTotalPrice());
            cartVOList.add(cartVO);
        }

        UserReceiveAddressVO userReceiveAddressVO = userReceiveAddressService.findDefaultAddress(userId);
        //如果没有默认地址，返回最新的收货地址当做默认地址
        if (userReceiveAddressVO == null) {
            List<UserReceiveAddress> userReceiveAddressList = userReceiveAddressService.selectAddressesByUserId(userId);
            if (!userReceiveAddressList.isEmpty()) {
                userReceiveAddressVO = new UserReceiveAddressVO();
                UserReceiveAddress userReceiveAddress = userReceiveAddressList.get(0);
                BeanUtil.copyOne(userReceiveAddress, userReceiveAddressVO);
            }
            //如果一个地址也没有，返回空
        }

        Map<String, Object> res = new HashMap<>();
        res.put("cartList", cartVOList);
        res.put("totalPrice", totalPrice);
        res.put("defaultAddress", userReceiveAddressVO);
        //把购物车选中项保存到session中
        httpSession.setAttribute("cartRes", res);
        return MapGenerator.getResWithData(200, "获取结算页面成功", res);
    }

    @Override
    public Map<String, Object> findSelectedProduct(Product product, Integer num, HttpSession httpSession) {
        UserVO userTemp = (UserVO) httpSession.getAttribute("user");
        String userId = userTemp.getUserId();

        BigDecimal totalPrice = product.getProductPrice().multiply(new BigDecimal(num));
        ProductDetailVO productDetailVO = new ProductDetailVO();
        BeanUtil.copyOne(product, productDetailVO);
        //把购买数量放到VO类中，此时amount代表购买数量，不代表库存数
        productDetailVO.setProductAmount(num);

        UserReceiveAddressVO userReceiveAddressVO = userReceiveAddressService.findDefaultAddress(userId);
        //如果没有默认地址，返回最新的收货地址当做默认地址
        if (userReceiveAddressVO == null) {
            List<UserReceiveAddress> userReceiveAddressList = userReceiveAddressService.selectAddressesByUserId(userId);
            if (!userReceiveAddressList.isEmpty()) {
                userReceiveAddressVO = new UserReceiveAddressVO();
                UserReceiveAddress userReceiveAddress = userReceiveAddressList.get(0);
                BeanUtil.copyOne(userReceiveAddress, userReceiveAddressVO);
            }
            //如果一个地址也没有，返回空
        }

        Map<String, Object> res = new HashMap<>();
        res.put("product", productDetailVO);
        res.put("totalPrice", totalPrice);
        res.put("defaultAddress", userReceiveAddressVO);
        //把商品选中项保存到session中
        httpSession.setAttribute("cartRes", res);
        return MapGenerator.getResWithData(200, "获取结算页面成功！", res);
    }

    private Cart selectCartByUserIdAndProductId(String userId, String productId) {
        if (!"".equals(userId) && !"".equals(productId)) {
            CartExample cartExample = new CartExample();
            cartExample.or().andUserIdEqualTo(userId).andProductIdEqualTo(productId).andIsDeletedEqualTo(0);
            List<Cart> cartList = cartDao.selectByExample(cartExample);
            if (cartList.isEmpty()) {
                return null;
            }
            return cartList.get(0);
        }
        return null;
    }
}
